<?php
/**
 * 转写文本处理类
 */
class Content
{
    //数组化文本
    protected $_arr;
    //文本格式化文本
    protected $_txt;
    //上一次结束时间
    protected $_last_time;
    //构造函数
    public function __construct($in = null)
    {
        if (is_array($in)) {
            $this->setJson($in);
        }
    }

    //设置初始文档
    public function setJson($arr)
    {
        $this->_arr = $arr;
        return $this;
    }

    //返回json格式转写结果
    public function getJson()
    {
        if (isset($this->_arr) && is_array($this->_arr)) {
            return json_encode($this->_arr, JSON_UNESCAPED_UNICODE);
        }
        throw new \Exception('array error');
    }

    //返回数组格式转写结果
    public function getArr()
    {
        return $this->_arr;
    }

    //返回文字格式转写结果
    public function getTxt()
    {
        return $this->_txt;
    }

    //重置
    public function initialize(){
        $this->_txt = null;
        $this->_arr = null;
        $this->_last_time = null;
    }

    /**
     * 转换成文字格式
     */
    public function deword()
    {
        if (!isset($this->_arr)) {
            throw new \Exception('array error');
        }
        $txt = '';
        $sc = 0;
        for($i = 0; $i<count($this->_arr);$i++)
        {
            if($sc != $this->_arr[$i]['sc']){
                $sc = $this->_arr[$i]['sc'];
                $txt .= '{$rep}'.$this->_arr[$i]['txt'];
                continue;
            }
            $txt .= $this->_arr[$i]['txt'];
        }
        return $txt;
    }

    /**
     * Json分段
     */
    public function paragraph_1()
    {
        if (isset($this->_arr)) {
            $sc = 0;
            foreach ($this->_arr as $k => &$v) {
                //if ($k == 0) {
                //$speech['lvsr_data'][$k]['txt'] = '&nbsp;&nbsp;' . $speech['lvsr_data'][$k]['txt'];
                //}
                if (mb_substr($v['txt'], -1, 1, 'utf-8') != '，') {
                    //$speech['lvsr_data'][$k + 1]['txt'] = '&nbsp;&nbsp;' . $speech['lvsr_data'][$k + 1]['txt'];
                    //$speech['lvsr_data'][$k + 1]['txt'] = '<br>' . $speech['lvsr_data'][$k + 1]['txt'];
                    $v['sc'] = $sc++;
                    //array_push($speech_result, $speech['lvsr_data'][$k]);
                    //array_push($speech_result, ['txt' => '<p></p>']);
                    continue;
                }
                $v['sc'] = $sc;
                //array_push($speech_result, $speech['lvsr_data'][$k]);
            }
        }
        return $this;
    }

    public function paragraph(){
        if(isset($this->_arr)) {
            for($i = 0; $i < count($this->_arr); $i++){
                $this->_arr[$i]['sc'] = $i;
            }
        }
        return $this;
    }

    /**
     * 后处理
     */
    public function reprocess()
    { }

    /**
     * 后处理还原
     */
    public function restore()
    { }

    /**
     * 去除语气词
     */
    public function modal()
    {
        if (isset($this->_arr)) {
            $json = json_encode($this->_arr, JSON_UNESCAPED_UNICODE);
            $origin_file = fopen('/home/wwwroot/default/data/lvsr.txt', 'w');
            $dest_file = fopen('/home/wwwroot/default/data/lvsr_oral.txt', 'w');
            fclose($dest_file);
            fwrite($origin_file, $json);
            fclose($origin_file);
            system('/home/wwwroot/default/data/run');
            $dest_file = fopen('/home/wwwroot/default/data/lvsr_oral.txt', 'r');
            $result = fread($dest_file, filesize("/home/wwwroot/default/data/lvsr_oral.txt"));
            fclose($dest_file);
            $json = str_replace(['"txt":",', '"txt":"}'], ['"txt":"",', '"txt":""}'], trim($result));
            $this->_arr = json_decode($json, true);
        }
        return $this;
    }

    /**
     * 获取摘要
     */
    public function abstract()
    {
        if (isset($this->_arr)) {
            $_txt = '';        
            foreach ($this->_arr as $val) {
                $_txt .= $val['txt'];
            }
            $_txt = str_replace("\n", "", $_txt);
            //
            $num = ceil(strlen($_txt)/(3*2000));
            //shell命令获取摘要
            $commond = 'python /home/wwwroot/default/data/summary.py ' . $num . ' ' . $_txt;
            exec($commond, $result);
            unset($result[0]);
            $_txt = '';
            for ($i = 1; $i <= $num; $i++) {
                $_txt .= $i . '、' . $result[$i] . "\n";
            }
            //$result = str_replace(["、，","、。","、？"], "、", $result);
            return $_txt;
        }
        throw new \Exception('array error');
    }

    /**
     * 按时间顺序 将文字添加如arr中
     * $content = new Content();
     * foreach($speech['list'] as $sentence){
     *    $content->push($sentence['txt'], $sentence['time']);
     * }
     * var_dump($content->getArr());
     */
    public function push($txt, $time, $sc = '', $speaker = '未标记')
    {
        //没有开始将文件制空
        if (!isset($this->_last_time)) {
            $this->_arr = [];
            $this->_last_time = 0;
        }
        $this->_arr[] = [
            'startTime' => strval($this->_last_time),
            'endTime' => strval($this->_last_time += $time),
            'txt' => $txt,
            'speaker' => $speaker,
            'sc' => $sc
        ];
        return $this;
    }

    /**
     * 转换arr, 为srt字幕格式文件
     */
    public function srt()
    {
        if (isset($this->_arr)) {
            $srt = '';
            for ($i = 0; $i < count($this->_arr); $i++) {
                $srt .= $i+1 . "\r\n" . $this->_srt($this->_arr[$i]) . "\r\n";
            }
            return $srt;
        }
        throw new \Exception('array error');
    }

    /**
     * 
     */
    protected function _srt($array)
    {
        $_str = $this->formatSeconds($array['startTime']) . " --> " . $this->formatSeconds($array['endTime']) . "\r\n" . $array['txt'];
        $_str = isset($array['translate']) ? $_str . "\r\n" . $array['translate'] : $_str;
        return $_str;
    }

    function formatSeconds($seconds)
    {
        $hours = 0;
        $milliseconds = str_replace("0.", '', $seconds - floor($seconds));

        if ($seconds > 3600) {
            $hours = floor($seconds / 3600);
        }
        $seconds = $seconds % 3600;


        return str_pad($hours, 2, '0', STR_PAD_LEFT)
            . gmdate(':i:s', $seconds)
            . ($milliseconds ? ",".substr($milliseconds,0,3) : ',000');
    }

    
}
